package com.isman.placeslist.ws;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import com.isman.placeslist.apiobject.Session;
import com.isman.placeslist.setting.ProjectPref;

import android.content.Context;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;

public class RESTClient {
	private static final String TAG = "RESTClient";
	private String BASE_URL = "http://10.0.2.2/l/lissystem/rest/";
	// private String BASE_URL = "http://192.168.137.1/l/lissystem/rest/";
	private int mTimeout = 3000;
	private Session mSession;
	private AsyncRunnerHeadler mHeadler;

	public RESTClient(Context mContext, AsyncRunnerHeadler mHeadler) {
		this.mSession = new Session();
		this.mHeadler = mHeadler;
		ProjectPref.restoreSession(mSession, mContext);
	}

	public HttpResponse Get(String path) {
		Log.i(TAG, BASE_URL + mSession.getId() + path);
		HttpResponse response = null;

		HttpGet get = new HttpGet(BASE_URL + mSession.getId() + path
				+ "?access_token=" + mSession.getToken());
		HttpClient client = getHttpClient();
		try {
			response = client.execute(get);
		} catch (ClientProtocolException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
			Log.i(TAG, e.getMessage());
		} catch (IOException e) {
			Log.i(TAG, e.getMessage());
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		}
		client.getConnectionManager().shutdown();
		return response;
	}

	public HttpResponse Post(String path, CustomMultiPartEntity entity) {
		Log.i(TAG, BASE_URL + mSession.getId() + path);
		HttpResponse response = null;

		HttpPost post = new HttpPost(BASE_URL + mSession.getId() + path
				+ "?access_token=" + mSession.getToken());
		HttpClient client = getHttpClient();


		post.setEntity(entity);
		try {
			response = client.execute(post);
			entity.consumeContent();
		} catch (ClientProtocolException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		} catch (IOException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		} finally {
			client.getConnectionManager().shutdown();
		}

		return response;
	}

	public HttpResponse Put(String path, Bundle bundle) {
		Log.i(TAG, BASE_URL + mSession.getId() + path);
		HttpResponse response = null;

		HttpPut put = new HttpPut(BASE_URL + mSession.getId() + path
				+ "?access_token=" + mSession.getToken());
		HttpClient client = getHttpClient();

		MultipartEntity entity = new MultipartEntity();

		if (bundle.containsKey("image")) {
			File file = new File(bundle.getString("image"));
			ContentBody cbFile = new FileBody(file, "image/jpeg");
			entity.addPart("image", cbFile);
			bundle.remove("image");
		}

		for (String key : bundle.keySet()) {
			try {
				entity.addPart(key, new StringBody(bundle.getString(key)));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		put.setEntity(entity);
		try {
			response = client.execute(put);
			entity.consumeContent();
		} catch (ClientProtocolException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		} catch (IOException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		}

		client.getConnectionManager().shutdown();
		return response;
	}

	public HttpResponse Delete(String path) {
		Log.i(TAG, BASE_URL + mSession.getId() + path);
		HttpResponse response = null;

		HttpDelete delete = new HttpDelete(BASE_URL + mSession.getId() + path
				+ "?access_token=" + mSession.getToken());
		HttpClient client = getHttpClient();
		try {
			response = client.execute(delete);
		} catch (ClientProtocolException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		} catch (IOException e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		}

		client.getConnectionManager().shutdown();
		return response;
	}

	private HttpClient getHttpClient() {
		HttpClient mClient = null;
		try {
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setUserAgent(params, System.getProperties()
					.getProperty("http.agent"));
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			HttpConnectionParams.setConnectionTimeout(params, mTimeout);
			mClient = new DefaultHttpClient(params);
		} catch (Exception e) {
			Looper.prepare();
			mHeadler.onConnectingError(e.getMessage());
			Looper.loop();
			e.printStackTrace();
		}
		return mClient;
	}
}
